<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/19
 * Time: 11:48
 */

namespace app\index\controller;
use app\console\model\Service;
use function GuzzleHttp\Psr7\str;
use think\Db;
use think\Exception;
use think\Loader;
use think\Request;
use think\Response;
class ServiceOrder extends Base
{
    /**
     * 码卷验证
     */
    public function check_code($order_number){

        $data = Db::name('order')->where('order_type',2)->where('order_number|shop_order_number',$order_number)->update(['code' =>2,'code_time' => date('Y-m-d H:i:s')]);

        if($data !== false){
            $str = '<script>alert("码卷验证成功")</script>';
           return response($str);
        }
        return 'fail';

    }


    public function qrcode($order_number)
    {
        Loader::import('phpqrcode.phpqrcode', EXTEND_PATH);
        $url = Request::instance()->domain().'/index.php/index/service_order/check_code/order_number/'.$order_number;
        $object = new \QRcode();
        $path = ROOT_PATH . 'public/index/service/' . $order_number . '.png';
        //第二个参数false的意思是不生成图片文件，如果你写上‘picture.png’则会在根目录下生成一个png格式的图片文件
        $ret = $object->png($url, false, 10, 10, 2);
        exit;
    }

    public function erweima($id)
    {
        Loader::import('phpqrcode.phpqrcode', EXTEND_PATH);
        $url = Request::instance()->domain().'/index.php/index/erweima/id/'.$id;
        $object = new \QRcode();
        $path = ROOT_PATH . 'public/index/erweima/' . $id . '.png';
        //第二个参数false的意思是不生成图片文件，如果你写上‘picture.png’则会在根目录下生成一个png格式的图片文件
        $ret = $object->png($url, false, 10, 10, 2);
        exit;
    }

    public function type()
    {
        //$result = Db::query('call protect_type()');
        $result = Db::name('protect_type')->select();
        return ['code' => '200', 'message' => '保单类型', 'data' => $result];
    }

    function gc(){
        $result = Db::query('call a');
        halt($result[0]);
    }

    public function evaluate_create($member_id, $order_number, $content, $single_id, $shop_id = 0)
    {
        try {
            if ($shop_id == 0) {
                $shop_id = Db::name('order')->where('order_number|shop_order_number', $order_number)->value('shop_id');
            }
            $order = Db::name('order')->where('order_number|shop_order_number', $order_number)->find();

            $parent_id = 0;
            $t_type = 1;
            if ($order['order_type'] == 3) {
                $parent_id = $single_id;//如果是礼包 父级和子集分类相同
                if($order['t_type'] == 2){
                    $t_type = 2;
                }

            }
            if ($order['order_type'] == 2) {
                $parent_id = Db::name('single')->where('id', $single_id)->value('parent_id');
            }

            $pic_url = uploadOne('pic_url');

            $insert = [
                't_type' => $t_type,
                'order_type' => $order['order_type'],
                'member_id' => $member_id,
                'order_number' => $order_number,
                'content' => $content,
                'pic_url' => $pic_url,
                'single_id' => $single_id,
                'shop_id' => $shop_id,
                'parent_id' => $parent_id,
                'create_time' => date('Y-m-d H:i:s', time())
            ];
            $data = Db::name('order_evaluate')->insert($insert);
            if ($data) {
                $ret = Db::name('order')->where('order_number|shop_order_number', $order_number)->where('status', 5)->setField('status', 4);
                if ($ret) {
                    return ['code' => 200, 'message' => '评价成功'];
                }
            }
            return ['code' => 400, 'message' => '失败'];
        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }


//    public function evaluate_index($order_number,$member_id){
//        $single_id = Db::name('order')->where('order_number',$order_number)->where('member_id',$member_id)->value('single_id');
//        $single_title = Db::name('single')->where('id',$single_id)->value('cat_name');
//        $single_pic_url = Db::name('single')->where('id',$single_id)->value('pic_url');
//        return ['code' => 200 ,'message' => '订单评价展示数据',];
//    }

    public function car_number($car_number,$member_id){
        if(empty($car_number)){
            //用于给前台下单使用
            $member_car_number = Db::name('member')->where('id',$member_id)->value('car_number');
            $member_car_list_car_number = Db::name('member_car_list')->where('member_id',$member_id)->column('car_number');
            if(empty($member_car_number)){
                $car_number = '';
            }
            if(!empty($member_car_number)){
                if(empty($member_car_list_car_number)){
                    $car_number = $member_car_number;
                }
            }
            if(!empty($member_car_number) && !empty($member_car_list_car_number)){
                $car_number = $member_car_number.'-'.implode('-',$member_car_list_car_number);
            }
        }
        return $car_number;
    }
    /**
     * @param $member_id
     * @param $type_id_str
     * @param $protecteder
     * @return array
     * 汽车保险
     */
    public function protect($device = 1,$shop_id = 0,$member_id,$type_id_str,$protecteder,$phone,$single_id,$plat_number,$plat_name,$engine_number,$brand_number,$plat_code,$register_time)
    {

        Db::startTrans();
        try {
            $protecter_face = uploadOne('protecter_face');
            $protecter_back = uploadOne('protecter_back');
            $car_face = uploadOne('car_face');
            $car_back = uploadOne('car_back');
            $order_number = order_number();
            $shop_order_number = shop_order_number($member_id);
            $time = date('Y-m-d H:i:s', time());
            $username = Db::name('member')->where('id', $member_id)->value('username');
            $single_parent_id = Db::name('single')->where('id', $single_id)->value('parent_id');
            $single_title  = Db::name('single')->where('id', $single_parent_id)->value('cat_name');
            $amount = Db::name('shop_service_price')->where('single_id', $single_id)->where('shop_id', $shop_id)->value('price');
            $sj = Db::name('shop_service_price')->where('single_id', $single_id)->where('shop_id', $shop_id)->value('sj');
            if(is_null($amount) || empty($amount) || $amount == '0.00'){
                //return ['code' => 400,'message' => '此门店服务金额未设置,请联系客服'];
            }
            if(is_null($sj) || empty($sj) || $sj =='0.00'){
                //return ['code' => 400,'message' => '此门店服务税金未设置,请联系客服'];
            }
            $sj = 0;
            $amount = 0;
            if($single_parent_id == 1){ //汽车保险 就是等待沟通
                $status = 50;
            }else{
                $status = 1;
            }
            $order = [
                'car_number' => $this->car_number('',$member_id),
                'device' => $device,
                'finance_order' => set_finance_order($member_id),
                'order_online' => 1,
                'shop_id' => $shop_id,
                'shipping' => 2,
                'order_number' => $order_number,
                'shop_order_number' => $shop_order_number,
                'order_type' => 2,
                'service_type_id' => 1,//1保险2年检3
                'single_id' => $single_id,
                'single_parent_id' => $single_parent_id,
                'per' => Db::name('single')->where('id',$single_id)->value('per'),
                'single_title' => $single_title,
                'member_id' => $member_id,
                'username' => $username,
                'amount' => $amount+$sj,
                'sj' => $sj,
                'order_price' => $amount,
                'pay_way' => '-',
//                'bill' => $bill,//是否开发票
//                'bill_type' => $bill_type,//是否开发票
//                'bill_header' => $bill_header,//是否开发票
//                'bill_content' => $bill_content,//是否开发票
//                'bill_email' => $bill_email,//是否开发票
//                'bill_phone' => $bill_phone,
                'status' => $status,//未支付-待支付
                'create_time' => date('Y-m-d H:i:s', time())
            ];
            $order_id = Db::name('order')->insertGetId($order);
            $protect = [
                'plat_number' => $plat_number,
                'plat_name' => $plat_name,
                'engine_number' => $engine_number,
                'brand_number' => $brand_number,
                'plat_code' => $plat_code,
                'register_time' => $register_time,
                'order_id' => $order_id,
                'order_number' => $order_number,
                'shop_order_number' => $shop_order_number,
                'type_id_str' => $type_id_str,
                'phone' => $phone,
                'protecteder' => $protecteder,
                'protecter_back' => $protecter_back,
                'protecter_face' => $protecter_face,
                'car_face' => $car_face,
                'car_back' => $car_back,
                'create_time' => $time,
            ];
            $protect_id = Db::name('order_service')->insertGetId($protect);
            Db::commit();
            return ['code' => 200,'message' => '保单提交成功','order_number' => $order_number];
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => $e->getCode(),'message' => $e->getMessage(),'line' => $e->getLine()];
        }

    }

    /**
     * @return array
     * 小程序图片单图上传
     */
    public function xiao_upload(){
        $protecter_face = uploadOne('image');
        return ['code' => 200,'message' => '图片上传成功','images_url' => $protecter_face];
}

    /**
     * @param $member_id
     * @param $protecteder
     * @param $phone
     * @return array
     * 汽车年检
     */
    public function year_check($device = 1,$shop_id = 0,$member_id,$protecteder,$phone,$single_id,$plat_number,$plat_name,$engine_number,$brand_number,$plat_code,$register_time){
        Db::startTrans();
        try {
            $protecter_face = uploadOne('protecter_face');
            $protecter_back = uploadOne('protecter_back');
            $car_face = uploadOne('car_face');
            $car_back = uploadOne('car_back');
            $order_number = order_number();
            $shop_order_number = shop_order_number($member_id);
            $time = date('Y-m-d H:i:s', time());
            $username = Db::name('member')->where('id', $member_id)->value('username');
            $single_parent_id = Db::name('single')->where('id', $single_id)->value('parent_id');
            $single_title  = Db::name('single')->where('id', $single_parent_id)->value('cat_name');
            $amount = Db::name('shop_service_price')->where('single_id', $single_id)->where('shop_id', $shop_id)->value('price');
            $sj = Db::name('shop_service_price')->where('single_id', $single_id)->where('shop_id', $shop_id)->value('sj');
            if(is_null($amount) || empty($amount) || $amount == '0.00'){
                return ['code' => 400,'message' => '此门店服务金额未设置,请联系客服'];
            }
            if(is_null($sj) || empty($sj) || $sj =='0.00'){
                //return ['code' => 400,'message' => '此门店服务税金未设置,请联系客服'];
            }
            $sj = 0;
            $order = [
                'car_number' => $this->car_number('',$member_id),
                'device' => $device,
                'finance_order' => set_finance_order($member_id),
                'order_online' => 1,
                'shop_id' => $shop_id,
                'shipping' => 2,
                'order_number' => $order_number,
                'shop_order_number' => $shop_order_number,
                'order_type' => 2,
                'service_type_id' => 2,//1保险2年检3直接提交 4是url汽车超市
                'single_id' => $single_id,
                'single_parent_id' => $single_parent_id,
                'per' => Db::name('single')->where('id',$single_id)->value('per'),
                'single_title' => $single_title,
                'member_id' => $member_id,
                'username' => $username,
                'amount' => $amount+$sj,
                'order_price' => $amount,
                'sj'  => $sj,
                'pay_way' => '-',
                'bill' => 2,//不开发票
                'status' => 1,//未支付-待支付
                'create_time' => date('Y-m-d H:i:s', time())
            ];
            $order_id = Db::name('order')->insertGetId($order);
            $protect = [
                'plat_number' => $plat_number,
                'plat_name' => $plat_name,
                'engine_number' => $engine_number,
                'brand_number' => $brand_number,
                'plat_code' => $plat_code,
                'register_time' => $register_time,
                'order_id' => $order_id,
                'order_number' => $order_number,
                'shop_order_number' => $shop_order_number,
                'phone' => $phone,
                'protecteder' => $protecteder,
                'protecter_back' => $protecter_back,
                'protecter_face' => $protecter_face,
                'car_face' => $car_face,
                'car_back' => $car_back,
                'create_time' => $time,
            ];
            $protect_id = Db::name('order_service')->insertGetId($protect);
            Db::commit();
            return ['code' => 200,'message' => '年检订单提交成功','order_number' => $order_number];
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => $e->getCode(),'message' => $e->getMessage(),'line' => $e->getLine()];
        }

    }

    /**
     * @param $order_number
     * @param $bill
     * @param $bill_phone
     * @param $bill
     * @param string $bill_type
     * @param string $bill_header
     * @param string $bill_content
     * @param string $bill_email
     * @return array
     * 是否开发票
     */

    public function bill($member_id,$order_number,$bill,$bill_phone,$bill_type = '',$bill_header = '',$bill_content = '',$bill_email = ''){
        try {
            $insert = [
                'bill' => $bill,//是否开发票
                'bill_type' => $bill_type,//是否开发票
                'bill_header' => $bill_header,//是否开发票
                'bill_content' => $bill_content,//是否开发票
                'bill_email' => $bill_email,//是否开发票
                'bill_phone' => $bill_phone,
            ];
            $ret = Db::name('order')->where('order_number|shop_order_number', $order_number)->where('member_id', $member_id)->update($insert);
            if ($ret !== false) {
                return ['code' => 200, 'message' => '订单发票信息修改成功', 'order_number' => $order_number];
            }
            return ['code' => 400, 'message' => '失败'];
        } catch (\Exception $e) {
            return ['message' => $e->getMessage()];
        }
    }


    public function remark($member_id,$order_number,$explain){

        $ret = Db::name('order')->where('order_number|shop_order_number', $order_number)->where('member_id', $member_id)->update(['explain' => $explain]);
        if ($ret !== false) {
            return ['code' => 200, 'message' => '修改备注信息成功', 'order_number' => $order_number];
        }
}

    /**
     * 洗车和轮胎
     */
    public function beauty_tires($device = 1,$shop_id = 0,$member_id,$single_id){
        Db::startTrans();
        try {
            $order_number = order_number();
            $shop_order_number = shop_order_number($member_id);
            $time = date('Y-m-d H:i:s', time());
            $username = Db::name('member')->where('id', $member_id)->value('username');
            $single_parent_id = Db::name('single')->where('id', $single_id)->value('parent_id');
            $single_title  = Db::name('single')->where('id', $single_parent_id)->value('cat_name');
            $amount = Db::name('shop_service_price')->where('single_id', $single_id)->where('shop_id', $shop_id)->value('price');
            $sj = Db::name('shop_service_price')->where('single_id', $single_id)->where('shop_id', $shop_id)->value('sj');

            if(is_null($amount) || empty($amount) || $amount =='0.00'){
                return ['code' => 400,'message' => '此门店服务金额未设置,请联系客服'];
            }
            if(is_null($sj) || empty($sj) || $sj =='0.00'){
                //return ['code' => 400,'message' => '此门店服务税金未设置,请联系客服'];
            }
            $sj = 0;
            $order = [
                'car_number' => $this->car_number('',$member_id),
                'device' => $device,
                'finance_order' => set_finance_order($member_id),
                'order_online' => 1,
                'shop_id' => $shop_id,
                'shipping' => 2,
                'order_number' => $order_number,
                'shop_order_number' => $shop_order_number,
                'order_type' => 2,
                'service_type_id' => 3,//1保险2年检3 4个没有附表的分类
                'single_id' => $single_id,
                'single_parent_id' => $single_parent_id,
                'per' => Db::name('single')->where('id',$single_id)->value('per'),
                'single_title' => $single_title,
                'member_id' => $member_id,
                'username' => $username,
                'amount' => $amount+$sj,
                'order_price' => $amount,
                'sj'  => $sj,
                'pay_way' => '-',
                'bill' => 2,//不开发票
                'status' => 1,//未支付-待支付
                'create_time' => date('Y-m-d H:i:s', time())
            ];
            $order_id = Db::name('order')->insertGetId($order);
            Db::commit();
            return ['code' => 200,'message' => $single_title.'-订单提交成功','order_number' => $order_number];
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => $e->getCode(),'message' => $e->getMessage(),'line' => $e->getLine()];
        }

    }


    public function time()
    {
        $param = Request::instance()->param();
        writeLog(var_export($param,true));
        $data = Db::name('time')->field('id,station_id,title,status')->where('status', 1)->order(['sort' => 'asc', 'id' => 'asc'])->where('station_id', $param['station_id'])->select()->toArray();
        foreach ($data as &$v) {

            $find = Db::name('service')->where('service_time', $v['title'])->where('status','in','1,2,3')->where('station_id', $param['station_id'])->where('shop_id', $param['shop_id'])->where('service_date', $param['service_date'])->find();

            if (empty($find)) {  //空不处理 还是开启
                $v['is_show'] = 1;//未预约

            }
//            if(!empty($find) && $find['stop_order'] == 2){
//                $v['is_show'] = 2;
//            }
            $start_time = strtotime($find['service_date'].' '.$v['title']);
            if (!empty($find)) {
               // dump($start_time);
                $v['is_show'] = 2; //已预约
            }
            $start_time = strtotime($find['service_date'].' '.explode('-', $v['title'])[0]);

            if(!empty($find && $find['status'] == 2)){
                $v['is_show'] = 3; //服务中 到店
                if(time() > $start_time){
                    $v['is_show'] = 4; //服务中 到店
                }

            }
            if(!empty($find && $find['status'] == 3)){
                $v['is_show'] = 4; //已完成

            }
//            dump($start_time);
//            $end_time = strtotime($find['service_date'].' '.explode('-', $v['title'])[1]);
//            if (!empty($find) && time() >= $start_time && time() <= $end_time) {
//                $v['is_show'] = 3; //已预约
//            }


        }
        return ['code' => 200, 'message' => '时间', 'data' => $data];
    }

    public function date()
    {
        $param = Request::instance()->param();
    }

    public function yuyue()
    {
        $param = Request::instance()->param();
        writeLog(json_encode($param));
        //预约范围;
        $time = Db::name('config')->where('varname', 'web_appointment_time')->value('varvalue');
        $fanweitime = $time * 60 * 60 * 24 + time();
//        if (strtotime($param['service_date'].' '.explode('-', $param['service_time'])[0]) > $fanweitime) {
//            return ['code' => 400, 'message' => '预约范围时间为' . $time . '天内'];
//        }
        if (strtotime($param['service_date'].' '. $param['service_time']) > $fanweitime) {
            return ['code' => 400, 'message' => '预约范围时间为' . $time . '天内'];
        }
//        return ['code' => 400, 'message' => '1'];
        $find2 = (new Service())->where('status','egt',1)->where('shop_id', $param['shop_id'])->where('service_date', $param['service_date'])->where('station_id', $param['station_id'])->where('service_time', $param['service_time'])->find();
        if (!empty($find2)) {
            return ['code' => 400, 'message' => '同一门店工位时间段只能预约一次'];
        }
        writeLog(json_encode($param));
        $start_time = strtotime(date("Y-m-d", time()));
        $end_time = $start_time + 60 * 60 * 24;
        //$where['create_time'] = ['between time', [$start_time, $end_time]];
        $where['service_date'] = ['eq',$param['service_date']];
        $find3 = (new Service())->where('member_id', $param['member_id'])->where('status','neq',-1)->where($where)->find();

        if (!empty($find3)) {
            return ['code' => 400, 'message' => '同一账号同一预约天只可预约一次'];
        }
        // $param['service_time_id'] = Db::name('time')->where('title',$param['service_time'])->value('sort');
        $param['service_time_id'] = explode('-', $param['service_time'])[0];
//        if (strtotime($param['service_date'] . ' ' . explode('-', $param['service_time'])[1]) < time()) {
//            return ['code' => 400, 'message' => '请选择将来时间'];
//        }

        if (strtotime($param['service_date'] . ' ' .$param['service_time']) < time()) {
            return ['code' => 400, 'message' => '请选择将来时间'];
        }

        $ret = (new Service())->save($param);

        $id =  Db::getLastInsID();
        if ($ret) {
            $shop_name = Db::name('shop')->where('id',$param['shop_id'])->value('shop_title');
            $single_name = Db::name('single')->where('id',$param['single_id'])->value('cat_name');
            $station_name = Db::name('station')->where('id',$param['station_id'])->value('title');
            $content = '服务:'.$single_name.' 工位:'.$station_name;
            $title = '预约门店:'.$shop_name.' 时间:'.$param['service_date'].' '.$param['service_time'];
            (new \app\index\controller\MemberMessage())->jpushMessage($param['member_id'],$title,$content,7);
            $insertAll = [
                'type_id' => 7,
                'member_id' => $param['member_id'],
                'title' => $title.' '.$content,
                'content' => $content,
                'create_time' => date('Y-m-d H:i:s',time()),
                'order_number' => $id,
                'message_id' => 0
            ];
            (new \app\index\model\MemberMessage())->insert($insertAll);
            return ['code' => 200, 'message' => '预约成功'];
        }
        return ['code' => 400, 'message' => '失败'];
    }

//    public function yuyue_status()
//    {
//        $param = Request::instance()->param();
//        //return ['code' => 400, 'message' => '相同时间段的门店服务不能重复预约'];
//        $find = (new Service())->where('shop_id', $param['shop_id'])->where('service_date', $param['service_date'])->where('station_id',$param['station_id'])->where('service_time', $param['service_time'])->value('stop_order');
//        if(empty($find)){
//            return ['code' => 200, 'message' => '没有预约过可以预约'];
//        }
//        if ($find == 1) {
//            return ['code' => 200, 'message' => '可以预约'];
//        }
//        if ($find == 2) {
//            return ['code' => 400, 'message' => '当前时间段预约已经关闭'];
//        }
//
//    }

    /**
     * 预约取消订单
     */
    public function yuyue_cancel($yuyue_id)
    {
       $ret = Db::name('service')->where('id',$yuyue_id)->where('status',1)->setField('status',-1);
       if($ret){
           return ['code' => 200, 'message' => '预约单取消成功'];
       }
        return ['code' => 400, 'message' => '预约单取消失败'];

    }

    public function tenmin()
    {
        $now_time = time();
        $data = Db::name('service')->where('status', 1)->select();

        if(!empty($data)) {
            foreach ($data as $v) {
                $yuyue_time = strtotime($v['service_date'] . ' ' . $v['service_time']);

                $conofig_time = Db::name('config')->where('varname','web_tiemout')->value('varvalue')*60;
                if ($now_time - $yuyue_time > $conofig_time) { //600
                    Db::name('service')->where('status', 1)->where('id', $v['id'])->update(['status'=> -1]);
                    $shop_name = Db::name('shop')->where('id',$v['shop_id'])->value('shop_title');
                    $single_name = Db::name('single')->where('id',$v['single_id'])->value('cat_name');
                    $station_name = Db::name('station')->where('id',$v['station_id'])->value('title');
                    $content = '预约已取消=>服务:'.$single_name.' 工位:'.$station_name;
                    $title = '预约门店:'.$shop_name.' 时间:'.$v['service_date'].' '.$v['service_time'];
                    (new \app\index\controller\MemberMessage())->jpushMessage($v['member_id'],$title,$content,7);
                    $insertAll = [
                        'type_id' => 7,
                        'member_id' => $v['member_id'],
                        'title' => $title.' '.$content,
                        'content' => $content,
                        'create_time' => date('Y-m-d H:i:s',time()),
                        'order_number' => $v['id'],
                        'message_id' => 0
                    ];
                    (new \app\index\model\MemberMessage())->insert($insertAll);
                }
            }
        }
        echo 1;
    }
    //工位
    public function station($shop_id)
    {
        $data = Db::name('station')->where('shop_id', $shop_id)->where('status', 1)->select();
        return ['code' => 200, 'message' => '工位信息', 'data' => $data];
    }

    public function shijian($station_id)
    {
        $data = Db::name('time')->where('station_id', $station_id)->order(['sort' => 'asc', 'id' => 'asc'])->select()->toArray();
        return ['code' => 200, 'message' => '时间', 'data' => $data];
    }

    public function yuyuelist($service_id)
    {
        $find = (new Service())->find($service_id);
        $data['shop_name'] = Db::name('shop')->where('id', $find['shop_id'])->value('shop_title');
        $data['cat_name'] = Db::name('single')->where('id', $find['single_id'])->value('cat_name');
        $data['station_name'] = Db::name('station')->where('id', $find['station_id'])->value('title');
        $data['service_date'] = $find['service_date'];
        $data['service_time'] = $find['service_time'];
        $data['status_id'] = $find['status'];
        if ($find['status'] == 1) {
            $data['status'] = '预约中';
        } elseif ($find['status'] == 2) {
            $data['status'] = '服务中';
        } elseif($find['status'] == 3) {
            $data['status'] = '已完成';
        }else{
            $data['status'] = '取消订单';
        }

        return ['code' => 200, 'message' => '我的预约信息', 'data' => $data];
    }


}